import { QueryHandler, IQueryHandler } from '@nestjs/cqrs'
import { GetUserAvatarQuery } from './get-user-avatar.query';
import { AvatarEntity } from '../entities/avatar.mysql.entity';
import { Inject, NotFoundException } from '@nestjs/common';
import { Repository } from 'typeorm';

@QueryHandler(GetUserAvatarQuery)
export class GetUserAvatarQueryHandler implements IQueryHandler<GetUserAvatarQuery> {
  constructor(
    @Inject('AVATAR_REPOSITORY')
    private readonly avatarRepository: Repository<AvatarEntity>,
  ) { }

  async execute(query: GetUserAvatarQuery) {
    const { userId } = query.params
    const [avatar] = await this.avatarRepository.find({ where: { userId }, order: { id: "DESC" } })
    if (!avatar) {
      throw new NotFoundException("用户头像不存在")
    }

    return avatar;
  }
}